<template>
  <div style="width:100%;height: 100%;display: flex;justify-content: center;align-items: center">
    <Select
      v-model:value="value"
      show-search
      allow-clear
      style="width:100%;height:100%"
      placeholder="请输入供应商关键词"
      :filter-option="false"
      :options="supplyOptions"
      :loading="supplyLoading"
      @search="handleSupplySearch"
      @dropdown-visible-change="handleSupplyDropdown"
      @change="handleSelectChange"
    />
  </div>
</template>

<script>
import { defineComponent, ref, onMounted, reactive, watch } from 'vue';
import { Select } from 'ant-design-vue';
import { useDebounceFn } from '@vueuse/core';
import {processIndex} from "#/api/spuBom/index.js";

export default defineComponent({
  components: {
    Select,
  },
  props: {
    params: Object,
  },
  setup(props) {
    const supplyOptions = ref([]);
    const supplyLoading = ref(false);

    const handleSupplySearch = useDebounceFn(async (keyword) => {
      supplyLoading.value = true;
      try {
        const  data= await processIndex({
          quick_search: keyword || '',
          page: 1,
          limit: 999,
          initKey: 'id',
          select: true,
        });
        supplyOptions.value = data.list.map((it) => ({ label: it.name, value: it.id }));
      } finally {
        supplyLoading.value = false;
      }
    }, 300);

    const handleSupplyDropdown = (open) => {
      if (open && supplyOptions.value.length === 0) {
        handleSupplySearch('');
      }
    };

    const value = ref(props.params?.value ?? '');
    const row = reactive(props.params.data);

    const getValue = () => row.process_name;

    const handleSelectChange = () => {
      const selectedOption = supplyOptions.value.find(option => option.value === value.value);
      if (selectedOption) {
        row.process_id = value.value; // 更新ID
        row.process_name = selectedOption.label; // 更新名称
      }
      props.params.api.stopEditing();
    };

    watch(
      () => supplyOptions.value,
      (newOptions) => {
        if (newOptions.length && value.value) {
          const selectedOption = newOptions.find(option => option.value === value.value);
          if (selectedOption) {
            row.process_name = selectedOption.label;
          }
        }
      }, { immediate: true }
    );

    onMounted(() => {
      handleSupplyDropdown(true);
    });

    return {
      supplyOptions,
      supplyLoading,
      handleSupplySearch,
      handleSupplyDropdown,
      value,
      row,
      getValue,
      handleSelectChange,
    };
  },
});
</script>

<style scoped>
input {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
</style>
